<template>
  <div class="login">
    <h1>登录</h1>
    <el-form
      :model="ruleForm"
      status-icon
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
      class="demo-ruleForm"
    >
      <el-form-item label="账号" prop="userName">
        <el-input
          type="text"
          v-model="ruleForm.userName"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="passWord">
        <el-input type="password" v-model.number="ruleForm.passWord"></el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')"
          >登录
        </el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator'
import { login } from '@/api/login'

@Component
export default class Login extends Vue {
  public nameMsg = '账号由字母开头3-8字母数字组成'
  public pwdMsg = '密码由6-16位字母数字下划线组成'

  public ruleForm = {
    userName: '',
    passWord: ''
  }

  public rules = {
    userName: [{ validator: this.validationName, trigger: 'blur' }],
    passWord: [
      {
        validator: this.validationPwd,
        trigger: 'blur'
      }
    ]
  }

  // 账号验证
  validationName (rule: any, value: string, callback: any) {
    if (value === '') return callback(new Error('请输入账号'))
    if (!/^[a-zA-z]\w{2,8}$/.test(value)) {
      return callback(new Error('账号格式错误  ' + this.nameMsg))
    }

    callback()
  }

  // 密码验证
  validationPwd (rule: any, value: string, callback: any) {
    if (value === '') return callback(new Error('请输入密码'))
    if (!/^[0-9A-Za-z_]{6,16}$/.test(value)) {
      return callback(new Error('账号格式错误  ' + this.pwdMsg))
    }

    callback()
  }

  // 点击提交按钮
  submitForm (formName: string) {
    (this.$refs[formName] as any).validate(async (valid: unknown) => {
      if (!valid) return false

      const { meta, data } = await login({
        username: this.ruleForm.userName,
        password: this.ruleForm.passWord
      })

      if (!(meta.status === 200)) {
        return this.$message({
          message: meta.msg,
          type: 'error'
        })
      }
      localStorage.setItem(
        'user',
        JSON.stringify({ name: data.username, token: data.token })
      )

      let num = 5
      this.open2(`登陆成功${num}秒后跳转到首页`)
      const timer = setInterval(() => {
        num--
        this.open2(`登陆成功${num}秒后跳转到首页`)
      }, 1000)
      setTimeout(() => {
        clearInterval(timer)
        this.$router.replace('/index')
      }, 5000)
    })
  }

  // 成功提示框
  open2 (smg = '登陆成功') {
    this.$message({
      message: smg,
      type: 'success'
    })
  }

  // 清除输入星系
  resetForm (formName: string) {
    (this.$refs[formName] as any).resetFields()
  }
}
</script>

<style lang="less" scoped>
.login {
  margin: 50px auto;
  width: 400px;
  h1 {
    text-align: center;
  }
}
</style>
